<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Homalos量化交易系统</title>
    <link rel="icon" type="image/svg+xml" href="/static/favicon.svg">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f5f7fa;
            color: #2c3e50;
            line-height: 1.6;
        }
        
        .header {
            background: linear-gradient(135deg, #409EFF 0%, #1890ff 100%);
            color: white;
            padding: 1rem 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            font-size: 1.8rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .header p {
            opacity: 0.9;
            font-size: 0.95rem;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
        }
        
        .dashboard {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 4px 6px rgba(0,0,0,0.05);
            border: 1px solid #e1e8ed;
            transition: all 0.3s ease;
        }
        
        .card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
        }
        
        .card-title {
            font-size: 1.2rem;
            font-weight: 600;
            margin-bottom: 1rem;
            color: #2c3e50;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #27ae60;
            animation: pulse 2s infinite;
        }
        
        .status-indicator.offline {
            background: #e74c3c;
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        
        .metric {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f3f4;
        }
        
        .metric:last-child {
            border-bottom: none;
        }
        
        .metric-label {
            color: #7f8c8d;
            font-size: 0.9rem;
        }
        
        .metric-value {
            font-weight: 600;
            color: #2c3e50;
        }
        
        .btn {
            display: inline-block;
            padding: 0.75rem 1.5rem;
            background: #409EFF;
            color: white;
            text-decoration: none;
            border-radius: 6px;
            font-weight: 500;
            border: none;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 0.9rem;
        }
        
        .btn:hover {
            background: #337ecc;
            transform: translateY(-1px);
        }
        
        .btn-secondary {
            background: #6c757d;
        }
        
        .btn-secondary:hover {
            background: #545b62;
        }
        
        .btn-success {
            background: #28a745;
        }
        
        .btn-success:hover {
            background: #218838;
        }
        
        .btn-danger {
            background: #dc3545;
        }
        
        .btn-danger:hover {
            background: #c82333;
        }
        
        .actions {
            display: flex;
            gap: 0.75rem;
            margin-top: 1rem;
            flex-wrap: wrap;
        }
        
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #409EFF;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .alert {
            padding: 1rem;
            border-radius: 6px;
            margin-bottom: 1rem;
        }
        
        .alert-info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-warning {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .footer {
            text-align: center;
            padding: 2rem;
            color: #7f8c8d;
            font-size: 0.9rem;
        }
        
        .hidden {
            display: none;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 1rem;
            }
            
            .dashboard {
                grid-template-columns: 1fr;
            }
            
            .actions {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <header class="header">
        <h1>🚀 Homalos量化交易系统</h1>
        <p>基于Python的期货量化交易系统 - 专业、稳定、高效</p>
    </header>
    
    <div class="container">
        <div id="alerts"></div>
        
        <div class="dashboard">
            <!-- 系统状态卡片 -->
            <div class="card">
                <h3 class="card-title">
                    <span class="status-indicator" id="system-status"></span>
                    系统状态
                </h3>
                <div class="metric">
                    <span class="metric-label">运行状态</span>
                    <span class="metric-value" id="system-running">检查中...</span>
                </div>
                <div class="metric">
                    <span class="metric-label">启动时间</span>
                    <span class="metric-value" id="system-uptime">--</span>
                </div>
                <div class="metric">
                    <span class="metric-label">网关连接</span>
                    <span class="metric-value" id="gateway-status">--</span>
                </div>
                <div class="metric">
                    <span class="metric-label">活跃策略</span>
                    <span class="metric-value" id="active-strategies">--</span>
                </div>
            </div>
            
            <!-- 账户信息卡片 -->
            <div class="card">
                <h3 class="card-title">💰 账户信息</h3>
                <div class="metric">
                    <span class="metric-label">总资产</span>
                    <span class="metric-value" id="total-balance">--</span>
                </div>
                <div class="metric">
                    <span class="metric-label">可用资金</span>
                    <span class="metric-value" id="available-balance">--</span>
                </div>
                <div class="metric">
                    <span class="metric-label">持仓市值</span>
                    <span class="metric-value" id="position-value">--</span>
                </div>
                <div class="metric">
                    <span class="metric-label">今日盈亏</span>
                    <span class="metric-value" id="daily-pnl">--</span>
                </div>
            </div>
            
            <!-- 策略管理卡片 -->
            <div class="card">
                <h3 class="card-title">📊 策略管理</h3>
                <div class="metric">
                    <span class="metric-label">已加载策略</span>
                    <span class="metric-value" id="loaded-strategies">--</span>
                </div>
                <div class="metric">
                    <span class="metric-label">运行中策略</span>
                    <span class="metric-value" id="running-strategies">--</span>
                </div>
                <div class="actions">
                    <button class="btn btn-success" onclick="discoverStrategies()">发现策略</button>
                    <button class="btn" onclick="refreshStrategies()">刷新状态</button>
                </div>
            </div>
            
            <!-- 交易监控卡片 -->
            <div class="card">
                <h3 class="card-title">📈 交易监控</h3>
                <div class="metric">
                    <span class="metric-label">今日成交</span>
                    <span class="metric-value" id="daily-trades">--</span>
                </div>
                <div class="metric">
                    <span class="metric-label">活跃订单</span>
                    <span class="metric-value" id="active-orders">--</span>
                </div>
                <div class="metric">
                    <span class="metric-label">持仓合约</span>
                    <span class="metric-value" id="position-count">--</span>
                </div>
                <div class="actions">
                    <a href="/docs" class="btn" target="_blank">API文档</a>
                    <button class="btn btn-secondary" onclick="refreshData()">刷新数据</button>
                </div>
            </div>
        </div>
        
        <!-- 快速操作区域 -->
        <div class="card">
            <h3 class="card-title">⚡ 快速操作</h3>
            <div class="actions">
                <button class="btn btn-success" onclick="startAllStrategies()">启动所有策略</button>
                <button class="btn btn-danger" onclick="stopAllStrategies()">停止所有策略</button>
                <button class="btn" onclick="exportData()">导出数据</button>
                <button class="btn btn-secondary" onclick="showSystemLogs()">查看日志</button>
            </div>
        </div>
    </div>
    
    <footer class="footer">
        <p>&copy; 2024 Homalos量化交易系统. 专业的期货量化交易解决方案.</p>
    </footer>
    
    <script>
        // 全局变量
        let systemData = {};
        let wsConnection = null;
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeSystem();
            connectWebSocket();
            setInterval(refreshData, 30000); // 每30秒刷新一次数据
        });
        
        // 初始化系统
        async function initializeSystem() {
            showAlert('系统正在初始化...', 'info');
            await refreshData();
        }
        
        // 刷新数据
        async function refreshData() {
            try {
                await Promise.all([
                    loadSystemStatus(),
                    loadAccountInfo(),
                    loadStrategiesInfo()
                ]);
                updateLastRefreshTime();
            } catch (error) {
                console.error('刷新数据失败:', error);
                showAlert('数据刷新失败: ' + error.message, 'error');
            }
        }
        
        // 加载系统状态
        async function loadSystemStatus() {
            try {
                const response = await fetch('/api/v1/system/status');
                const result = await response.json();
                
                if (result.success) {
                    systemData.status = result.data;
                    updateSystemStatusUI(result.data);
                } else {
                    throw new Error(result.message);
                }
            } catch (error) {
                console.error('加载系统状态失败:', error);
                updateSystemStatusUI(null);
            }
        }
        
        // 加载账户信息
        async function loadAccountInfo() {
            try {
                const response = await fetch('/api/v1/account');
                const result = await response.json();
                
                if (result.success) {
                    systemData.account = result.data;
                    updateAccountInfoUI(result.data);
                } else {
                    throw new Error(result.message);
                }
            } catch (error) {
                console.error('加载账户信息失败:', error);
                updateAccountInfoUI(null);
            }
        }
        
        // 加载策略信息
        async function loadStrategiesInfo() {
            try {
                const response = await fetch('/api/v1/strategies');
                const result = await response.json();
                
                if (result.success) {
                    systemData.strategies = result.data.strategies;
                    updateStrategiesInfoUI(result.data.strategies);
                } else {
                    throw new Error(result.message);
                }
            } catch (error) {
                console.error('加载策略信息失败:', error);
                updateStrategiesInfoUI(null);
            }
        }
        
        // 更新系统状态UI
        function updateSystemStatusUI(data) {
            const statusIndicator = document.getElementById('system-status');
            const runningElement = document.getElementById('system-running');
            const uptimeElement = document.getElementById('system-uptime');
            const gatewayElement = document.getElementById('gateway-status');
            const strategiesElement = document.getElementById('active-strategies');
            
            if (data) {
                statusIndicator.className = 'status-indicator';
                runningElement.textContent = '正常运行';
                uptimeElement.textContent = formatUptime(data.uptime || 0);
                gatewayElement.textContent = data.gateway_connected ? '已连接' : '未连接';
                strategiesElement.textContent = data.active_strategies || 0;
            } else {
                statusIndicator.className = 'status-indicator offline';
                runningElement.textContent = '连接失败';
                uptimeElement.textContent = '--';
                gatewayElement.textContent = '--';
                strategiesElement.textContent = '--';
            }
        }
        
        // 更新账户信息UI
        function updateAccountInfoUI(data) {
            const totalBalance = document.getElementById('total-balance');
            const availableBalance = document.getElementById('available-balance');
            const positionValue = document.getElementById('position-value');
            const dailyPnl = document.getElementById('daily-pnl');
            
            if (data) {
                totalBalance.textContent = formatCurrency(data.total_balance || 0);
                availableBalance.textContent = formatCurrency(data.available_balance || 0);
                positionValue.textContent = formatCurrency(data.position_value || 0);
                dailyPnl.textContent = formatCurrency(data.daily_pnl || 0);
                
                // 根据盈亏设置颜色
                const pnl = data.daily_pnl || 0;
                dailyPnl.style.color = pnl >= 0 ? '#27ae60' : '#e74c3c';
            } else {
                totalBalance.textContent = '--';
                availableBalance.textContent = '--';
                positionValue.textContent = '--';
                dailyPnl.textContent = '--';
            }
        }
        
        // 更新策略信息UI
        function updateStrategiesInfoUI(strategies) {
            const loadedElement = document.getElementById('loaded-strategies');
            const runningElement = document.getElementById('running-strategies');
            
            if (strategies) {
                const loaded = Object.keys(strategies).length;
                const running = Object.values(strategies).filter(s => s.status === 'running').length;
                
                loadedElement.textContent = loaded;
                runningElement.textContent = running;
            } else {
                loadedElement.textContent = '--';
                runningElement.textContent = '--';
            }
        }
        
        // 连接WebSocket
        function connectWebSocket() {
            try {
                const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
                const wsUrl = `${protocol}//${window.location.host}/ws/realtime`;
                
                wsConnection = new WebSocket(wsUrl);
                
                wsConnection.onopen = function() {
                    console.log('WebSocket连接已建立');
                    showAlert('实时数据连接已建立', 'success');
                };
                
                wsConnection.onmessage = function(event) {
                    try {
                        const message = JSON.parse(event.data);
                        handleWebSocketMessage(message);
                    } catch (error) {
                        console.error('解析WebSocket消息失败:', error);
                    }
                };
                
                wsConnection.onclose = function() {
                    console.log('WebSocket连接已关闭');
                    showAlert('实时数据连接已断开，尝试重连...', 'warning');
                    setTimeout(connectWebSocket, 5000);
                };
                
                wsConnection.onerror = function(error) {
                    console.error('WebSocket错误:', error);
                };
                
                // 发送心跳
                setInterval(() => {
                    if (wsConnection && wsConnection.readyState === WebSocket.OPEN) {
                        wsConnection.send(JSON.stringify({type: 'ping'}));
                    }
                }, 30000);
                
            } catch (error) {
                console.error('WebSocket连接失败:', error);
            }
        }
        
        // 处理WebSocket消息
        function handleWebSocketMessage(message) {
            if (message.type === 'event') {
                console.log('收到事件:', message.event_type, message.data);
                
                // 根据事件类型更新UI
                if (message.event_type.startsWith('strategy.')) {
                    refreshStrategies();
                } else if (message.event_type.startsWith('order.')) {
                    // 可以添加订单更新逻辑
                }
            }
        }
        
        // 发现策略
        async function discoverStrategies() {
            try {
                showAlert('正在发现可用策略...', 'info');
                const response = await fetch('/api/v1/strategies/discover');
                const result = await response.json();
                
                if (result.success) {
                    const strategies = result.data.available_strategies;
                    showAlert(`发现 ${strategies.length} 个可用策略`, 'success');
                    console.log('可用策略:', strategies);
                } else {
                    throw new Error(result.message);
                }
            } catch (error) {
                showAlert('策略发现失败: ' + error.message, 'error');
            }
        }
        
        // 刷新策略状态
        async function refreshStrategies() {
            await loadStrategiesInfo();
        }
        
        // 启动所有策略
        async function startAllStrategies() {
            if (!confirm('确定要启动所有策略吗？')) return;
            
            try {
                showAlert('正在启动所有策略...', 'info');
                // 这里需要实现批量启动逻辑
                showAlert('功能开发中...', 'warning');
            } catch (error) {
                showAlert('启动策略失败: ' + error.message, 'error');
            }
        }
        
        // 停止所有策略
        async function stopAllStrategies() {
            if (!confirm('确定要停止所有策略吗？')) return;
            
            try {
                showAlert('正在停止所有策略...', 'info');
                // 这里需要实现批量停止逻辑
                showAlert('功能开发中...', 'warning');
            } catch (error) {
                showAlert('停止策略失败: ' + error.message, 'error');
            }
        }
        
        // 导出数据
        function exportData() {
            showAlert('数据导出功能开发中...', 'warning');
        }
        
        // 显示系统日志
        function showSystemLogs() {
            showAlert('日志查看功能开发中...', 'warning');
        }
        
        // 显示提示信息
        function showAlert(message, type = 'info') {
            const alertsContainer = document.getElementById('alerts');
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type}`;
            alertDiv.textContent = message;
            
            alertsContainer.appendChild(alertDiv);
            
            // 3秒后自动移除
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.parentNode.removeChild(alertDiv);
                }
            }, 3000);
        }
        
        // 格式化货币
        function formatCurrency(amount) {
            return new Intl.NumberFormat('zh-CN', {
                style: 'currency',
                currency: 'CNY',
                minimumFractionDigits: 2
            }).format(amount);
        }
        
        // 格式化运行时间
        function formatUptime(seconds) {
            const days = Math.floor(seconds / 86400);
            const hours = Math.floor((seconds % 86400) / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            
            if (days > 0) {
                return `${days}天 ${hours}小时`;
            } else if (hours > 0) {
                return `${hours}小时 ${minutes}分钟`;
            } else {
                return `${minutes}分钟`;
            }
        }
        
        // 更新最后刷新时间
        function updateLastRefreshTime() {
            console.log('数据已刷新:', new Date().toLocaleTimeString());
        }
    </script>
</body>
</html>